package com.linser.gistools.refactoring.geotools.tools;

import javafx.application.Platform;
import javafx.scene.control.TextField;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.renderer.lite.RendererUtilities;
import org.geotools.swing.JMapPane;
import org.geotools.swing.event.MapMouseEvent;
import org.geotools.swing.tool.AbstractZoomTool;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.operation.TransformException;

import javax.swing.*;
import java.text.DecimalFormat;

/**
 * @author: linser
 * @Desc: 滚轮
 * @create: 2024-03-17 18:24
 **/
public class ScaleDisplayTool extends AbstractZoomTool {

    private final TextField scaleText;
    public ScaleDisplayTool(JMapPane mapPane,TextField ScaleText){
        this.setMapPane(mapPane);
        this.scaleText = ScaleText;
    }

    @Override
    public void onMouseWheelMoved(MapMouseEvent ev) {
        try {
            this.updateMapScale();
        } catch (FactoryException | TransformException e) {
            throw new RuntimeException(e);
        }
    }
    private void updateMapScale() throws FactoryException, TransformException {
        // 获取当前地图的显示范围（Envelope）
        ReferencedEnvelope envelope = this.getMapPane().getMapContent().getViewport().getBounds();

        // 计算地图的宽度（以地图单位计）
        double mapWidth = envelope.getWidth();
        // 获取地图视图的像素宽度
        double screenWidth = ((JComponent)this.getMapPane()).getVisibleRect().getWidth();
        if(mapWidth > 0 && screenWidth > 0){
            double metersMapWidth = RendererUtilities.toMeters(mapWidth , envelope.getCoordinateReferenceSystem());
            double scale = metersMapWidth/screenWidth;
            //此处不能在主线程频繁调用，不然会造成线程阻塞
            Platform.runLater(() -> {
                // 创建 DecimalFormat 对象，并设置格式化模式
                DecimalFormat decimalFormat = new DecimalFormat("#.###");
                scaleText.setText("1:" + decimalFormat.format(scale));
            });
        }
    }
}
